package com.sgj.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.sgj.springcloud.entities.CommonResult;
import com.sgj.springcloud.entities.Payment;
import com.sgj.springcloud.enums.ResEnum;
import com.sgj.springcloud.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author 沈国纪
 * @date 2021/6/5 13:15
 */
@RestController
public class CircleBreakerController {

	public static final String SERVICE_URL = "http://nacos-payment-provider";

	@Autowired
	private RestTemplate restTemplate;

	@Resource
	private PaymentService paymentService;

	@RequestMapping("/consumer/fallback/{id}")
	// @SentinelResource(value = "fallback") // 没有配置
	// @SentinelResource(value = "fallback", fallback = "handlerFallback") // fallback 只负责业务异常
	// @SentinelResource(value = "fallback", blockHandler = "blockHandler") // blockHandler 只负责 Sentinel 控制台配置违规
	@SentinelResource(value = "fallback", fallback = "handlerFallback", blockHandler = "blockHandler", exceptionsToIgnore = {IllegalArgumentException.class})
	public CommonResult<Payment> fallback(@PathVariable("id") Long id) {
		CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class, id);

		if (id == 4) {
			throw new IllegalArgumentException("IllegalArgumentException, 非法参数异常....");
		} else if (Objects.isNull(result.getData())) {
			throw new NullPointerException("NullPointerException, 该 ID 没有对应记录，空指针异常");
		}
		return result;
	}

	@GetMapping("/consumer/paymentSQL/{id}")
	public CommonResult<Payment> paymentSQL(@PathVariable("id")Long id){
		return paymentService.paymentSQL(id);
	}


	public CommonResult handlerFallback(@PathVariable("id") Long id, Throwable e) {
		Payment payment = new Payment(id, "null");
		return new CommonResult(ResEnum.HANDLER_FALLBACK.getCode(), ResEnum.HANDLER_FALLBACK.getMessage() + e.getMessage(), payment);
	}

	public CommonResult blockHandler(@PathVariable("id") Long id, BlockException blockException) {
		Payment payment = new Payment(id, "null");
		return new CommonResult(ResEnum.HANDLER_BLOCKHANDLER.getCode(), ResEnum.HANDLER_BLOCKHANDLER .getMessage() + blockException.getMessage(), payment);
	}
}